package com.home.school.controller;

import com.home.school.model.R;
import com.home.school.service.QiniuCloudService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 */
@RestController
@RequestMapping("/api/upload")
public class ImageController {

    @Resource
    private QiniuCloudService qiniuCloudService;

    @Value("${web.upload.image}")
    private String imageUrl;

    @RequestMapping("image")
    public R image(@PathVariable MultipartFile file) {
        String imageUrl = uploadFile(file);
        return R.ok().data(imageUrl);
    }


    private String uploadFile(MultipartFile image){
        // 获取原文件名
        String name = image.getOriginalFilename();
        // 获取文件后缀
        String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());
        // 日期文件夹
        String nowFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
        // 新的文件名以日期命名:
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "." + subffix;
        String upload = qiniuCloudService.upload(image, fileName);
        return upload;
    }

}
